﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Web;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using System.Collections;
using Microsoft.Office.Interop.Outlook;

namespace Outlook2010Translate
{
    partial class TranslateRegion
    {
        #region Form Region Factory



        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Note)]
        [Microsoft.Office.Tools.Outlook.FormRegionName("Outlook2010Translate.TranslateRegion")]
        public partial class TranslateRegionFactory
        {

            // Occurs before the form region is initialized.
            // To prevent the form region from appearing, set e.Cancel to true.
            // Use e.OutlookItem to get a reference to the current Outlook item.
            private void TranslateRegionFactory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
            {

                Outlook.MailItem item = e.OutlookItem as Outlook.MailItem;
                if (item != null)
                {
                    if (String.IsNullOrEmpty(item.Body))
                    {
                        e.Cancel = true;
                    }
                    else
                    {
                    }
                }
            }

        #endregion

            // Occurs before the form region is displayed.
            // Use this.OutlookItem to get a reference to the current Outlook item.
            // Use this.OutlookFormRegion to get a reference to the form region.
            private void TranslateRegion_FormRegionShowing(object sender, System.EventArgs e)
            {

            }

            // Occurs when the form region is closed.
            // Use this.OutlookItem to get a reference to the current Outlook item.
            // Use this.OutlookFormRegion to get a reference to the form region.
            private void TranslateRegion_FormRegionClosed(object sender, System.EventArgs e)
            {

            }

        }

        /// <summary>
        /// Handles the FormRegionShowing event of the TranslateRegion control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TranslateRegion_FormRegionShowing(object sender, EventArgs e)
        {

            Outlook.MailItem myItem = (Outlook.MailItem)this.OutlookItem;
            toolStripTextBoxAPIKey.Text = Properties.Settings.Default.GoogleAPITranslateKey;
            Sensitivity(myItem);
            SortedSet<AddValue> sl = new SortedSet<AddValue>();

            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
            {
                AddValue addedValue = new AddValue(ci.DisplayName, ci.TwoLetterISOLanguageName);
                if (!sl.Contains<AddValue>(addedValue) && !ci.TwoLetterISOLanguageName.Equals("iv", StringComparison.OrdinalIgnoreCase))
                {
                    sl.Add(addedValue);

                }

            }

            comboBox2.DisplayMember = "Display";
            comboBox2.ValueMember = "Value";
            comboBox2.DataSource = sl.ToList<AddValue>();
            comboBox2.SelectedValue = Properties.Settings.Default.ValueLocale;

        }

        /// <summary>
        /// If Sensitivities in mail is different then normal - Then disable translate.
        /// </summary>
        /// <param name="myItem">My item.</param>
        private void Sensitivity(Outlook.MailItem myItem)
        {
            if (myItem.Sensitivity != Outlook.OlSensitivity.olNormal)
            {
                menuStrip1.Enabled = false;
                btnTranslate.Enabled = false;
                txtTranslateWindow.Text = "This mail is having sensitivy higer than normal. Because of use of Google API this may be insecure to translate this over internet.";
                txtTranslateWindow.Enabled = false;
            }
            else
            {
                menuStrip1.Enabled = true;
                btnTranslate.Enabled = true;
                txtTranslateWindow.Enabled = true;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnTranslate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnTranslate_Click(object sender, EventArgs e)
        {
            Outlook.MailItem myItem = (Outlook.MailItem)this.OutlookItem;
            //string queryString = HttpUtility.UrlEncode(myItem.Body);
            if (myItem != null)
            {

                string sGoogleTranslateAPIKey = Properties.Settings.Default.GoogleAPITranslateKey;

                try
                {

                    btnTranslate.Enabled = false;
                    btnTranslate.Text = "Translating";
                    txtTranslateWindow.Text = TranslateText(sGoogleTranslateAPIKey, Properties.Settings.Default.ValueLocale.ToString());

                }
                finally
                {

                    btnTranslate.Text = "Translate";
                    btnTranslate.Enabled = true;

                }


            }
        }

        /// <summary>
        /// Translates the text.
        /// </summary>
        /// <param name="sGoogleTranslateAPIKey">The s google translate API key.</param>
        /// <param name="sLocale">The s locale.</param>
        /// <returns></returns>
        private string TranslateText(string sGoogleTranslateAPIKey, string sLocale)
        {
            string contentToTranslate = txtTranslateWindow.Text.Trim();
            string translatedText = String.Empty;

            if (String.IsNullOrEmpty(contentToTranslate))
            {
                return String.Empty;
            }
            ArrayList alToTranslate = new ArrayList();
            StringBuilder sbAggregatedTranslation = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            int x = 0;
            foreach (char c in contentToTranslate)
            {
                if (x == 400)
                {
                    alToTranslate.Add(sb.ToString());
                    sb.Clear();
                    x = 0;
                }
                else
                {
                    sb.Append(c);
                    x++;
                }
            }

            if (sb != null)
            {
                alToTranslate.Add(sb.ToString());
            }


            foreach (string item in alToTranslate)
            {
                WebResponse resp = null;
                try
                {
                    string sKey = String.Empty;
                    if (!String.IsNullOrEmpty(sGoogleTranslateAPIKey))
                    {
                        sKey = "&key=" + sGoogleTranslateAPIKey;
                    }
                    Uri url = new Uri("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&format=text&q=" + HttpUtility.UrlEncode(item) + sKey + "&userip=" + Dns.GetHostName() + "&langpair=%7C" + sLocale);
                    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                    //myReq.Referer = "Outlook2010Translate";
                    resp = myReq.GetResponse();
                    StreamReader readStream = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                    string JsonObject = readStream.ReadLine();
                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(JsonObject)))
                    {
                        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TranslateResponse));
                        TranslateResponse translation = ser.ReadObject(ms) as TranslateResponse;
                        switch (translation.responseStatus)
                        {
                            case "200":
                                sbAggregatedTranslation.Append(HttpUtility.UrlDecode(translation.responseData.translatedText));
                                break;
                            case "400":
                                sbAggregatedTranslation.Append("Not currently supported language - Sorry. " + translation.responseDetails);
                                break;
                            default:
                                sbAggregatedTranslation.Append(translation.responseDetails);
                                break;
                        }

                    }
                }
                finally
                {
                    resp.Close();
                }

            }

            return sbAggregatedTranslation.ToString();
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtTranslateWindow.Text))
            {
                Clipboard.SetData(DataFormats.Text, txtTranslateWindow.Text);
            }
        }



        #region Events
        private void clearTextToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtTranslateWindow.Clear();
        }

        private void toolStripTextBoxAPIKey_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                Properties.Settings.Default.GoogleAPITranslateKey = toolStripTextBoxAPIKey.Text;
                Properties.Settings.Default.Save();
                toolStripTextBoxAPIKey.SelectAll();
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("This application uses Google Translate API. Beware not to send any sensitive data to translate because of the use of internet when quering for translation.", "Outlook Translate Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Set your'e own Google API Key.", "Outlook Translate Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (comboBox2.SelectedItem is AddValue)
            {
                Properties.Settings.Default.DisplayNameLocale = ((AddValue)comboBox2.SelectedItem).Display;
                Properties.Settings.Default.ValueLocale = ((AddValue)comboBox2.SelectedItem).Value;
                Properties.Settings.Default.Save();
            }
        }
        #endregion

        #region TranslateTextBoxEvents
        private void txtTranslateWindow_DragDrop(object sender, DragEventArgs e)
        {
            string droppedText = (string)e.Data.GetData(DataFormats.Text);

            if (droppedText.Length > 500)
            {
                txtTranslateWindow.Text = droppedText.Substring(0, 500);
            }
            else
            {
                txtTranslateWindow.Text = droppedText;
            }
        }

        private void txtTranslateWindow_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void txtTranslateWindow_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                txtTranslateWindow.SelectAll();
                e.Handled = true;
            }
        }
        #endregion


    }
}
